<template>
  <view>
    <loading :showLoaded.sync="showLoaded"></loading>
    <view>
      <view v-for="(item, index) in rootcateList" :key="index">
        <view class="">
          <view class="titleBox">
            <view class="j_icon">{{item.navName}}</view>
            <view @click="enterProductList(item)">即刻探索<label class="macallan-icon mcl-youjiantou"></label></view>
          </view>
          <view class="bannerBox">
            <image @click="enterProductList(item)" style="width:100%;display:block;" mode="widthFix"
              :src="item.cmsImageSrc || 'https://100000063-1252208446.file.myqcloud.com/images/TempImg/bannerImg_1_0705.jpg'"></image>
          </view>
        </view>
        <itemsSlideslipNew v-if="item.navName == '不凡甄选' || item.navName == '璀璨系列'" :list.sync="contentLsitObj[item.foreignId].list" :navInfo.sync="item"></itemsSlideslipNew>
        <itemsTileNew v-else :list.sync="contentLsitObj[item.foreignId].list" :navInfo.sync="item"></itemsTileNew>
      </view>
    </view>
  </view>
</template>

<script>
  import api from '@/api/api';
  import tip from '@/utils/tip';
  import util from '@/utils/util.js'
  import loading from '@/components/common/loading';
  import itemsSlideslipNew from './itemsSlideslipNew.vue';
  import itemsTileNew from './itemsTileNew.vue';
  import {
    SYSTEM_INFO,
    MERCHANT_INFO,
    CUSTOMER_INFO
  } from '@/utils/constant';
  export default {
    components: {
      itemsSlideslipNew: itemsSlideslipNew,
      itemsTileNew: itemsTileNew,
      loading: loading,
    },
    data() {
      return {
        storeProductList: [],
        currentPage: 1,
        pageSize: 50,
        pageTotal: 0,
        rootcateList: [],
        afterPage: '',
        contentLsitObj: {},
        showLoaded: true,
        preview: false,
      }
    },

    onShow() {

    },
    methods: {
      initData: async function (option) {
        await this.$onLaunched;
        let that = this
        this.preview = getApp().globalData.cmsPreview ? getApp().globalData.cmsPreview : false;
        that.$commonFunction.getRootCateTopLevel().then(async (res) => {
          for (let i = 0; i < res.length; i++) {

            const item = res[i];
            await this.$commonFunction.getCmsInfo(item.foreignId, this.preview).then((cmsInfoRes) => {
              item.cmsImageSrc = cmsInfoRes.src
            }).catch((cmsInfoErr) => {
            });
            that.contentLsitObj[item.foreignId] = {}
            if (item.foreignId == 0) {
              await that.getStoreGoods().then((getStoreGoodsRes) => {
                that.contentLsitObj[item.foreignId].list = getStoreGoodsRes
              }).catch((getStoreGoodsErr) => {
              });
            } else {
              await that.getCateGoods(item.foreignId, '').then((getCateGoodsRes) => {
                that.contentLsitObj[item.foreignId].list = getCateGoodsRes
              }).catch((getCateGoodsErr) => {
              });
            }
          }
          that.showLoaded = false
          that.rootcateList = res;
        }).catch((err) => {
        });
      },
      // 获取门店商品
      getStoreGoods: async function() {
        return new Promise(async (resolve, reject) => {
          let that = this;
          let merchantInfo = uni.getStorageSync('merchantInfo')
          // 获取门店商品列表
          const json = await api.getStoreGoodsList({
            query: {
              merchantId: merchantInfo.cloudMerchantId,
              page: that.currentPage,
              size: that.pageSize,
            }
          });
          if (json.code === 1000) {
            this.storeProductList = json.data.content;
            resolve(json.data.content)
          }
        })
      },
      /**
       * 分类商品列表
       */
      getCateGoods: async function(class_id, is_sort) {
        return new Promise(async (resolve, reject) => {
          let that = this;
          let customerInfo = uni.getStorageSync('customerInfo');
          let memberDetails = uni.getStorageSync('memberDetails')
          let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
          let after = that.currentPage == 1 ? '' : that.afterPage
          that.$commonFunction.doSearchGoods(class_id, '', that.currentPage, that.pageSize, after, '', is_sort,
            '', '', '', '').then((res) => {
            that.afterPage = res.data.afterPage
            var cateProductList = res.data.content;
            let itemsList = res.data;
            that.page_total = Math.ceil(res.data.total / 16);
            // 策略价格
            var s_item = [];
            for (var i in cateProductList) {
              s_item = cateProductList[i];
              if (!!cateProductList[i].strategies) {

                that.$commonFunction.priceRulesDeal(cateProductList[i].strategies, cateProductList[i]
                  .itemCode).then(res => {
                  if (res.price !== 0) {
                    cateProductList.map(itey => {
                      if (itey.itemCode == res.itemCode) {
                        itey.price = res.price
                      }
                    })
                  }
                  if (res.rulesArr.length > 0) {
                    cateProductList.map(itey => {
                      if (itey.itemCode == res.itemCode) {
                        itey.rulesArr = res.rulesArr
                      }
                    })
                  }
                }).catch(err => {
                })
              }

              var customPromotionTags = [];
              var isForwardpurchaseGoods = false;
              if (s_item['promotionTagList']) {
                for (var t in s_item['promotionTagList']) {
                  var tagItem = s_item['promotionTagList'][t];
                  if (tagItem.promotionType == 'custom_tag') {
                    customPromotionTags.push(tagItem);
                  }

                  if (tagItem.promotionType == 'forward_purchase') {
                    isForwardpurchaseGoods = true;
                  }
                }
                let tempTagList = customPromotionTags.slice();
                tempTagList.sort((a, b) => {
                  return a.sortOrder - b.sortOrder;
                });
                that.customPromotionArr = tempTagList;
              }

            }
            let temporaryProductList = cateProductList
            for (let i = 0; i < cateProductList.length; i++) {
              if (cateProductList[i].skuCodes !== undefined) {
                this.$sr.track('expose_sku_component', {
                  sku: {
                    sku_id: cateProductList[i].skuCodes[0].toString(),
                    sku_name: cateProductList[i].itemName // 若商品无sku_name时，可传spu_name信息
                  },
                  spu: {
                    spu_id: 
              !!uni.getStorageSync('openOuterItemId') ? cateProductList[i].outerItemId : !!uni.getStorageSync('youshuOpencc') ? cateProductList[i].frontCode
                      .toString() : cateProductList[i].itemCode.toString(),
                    spu_name: !!uni.getStorageSync('youshuOpencc') ? cateProductList[i].itemName +
                      cateProductList[i].valueName : cateProductList[i]
                      .itemName // 若商品无spu_name时，可传sku_name信息
                  },
                  sku_category: [{
                    sku_cat_id: cateProductList[i].categoryId.toString(),
                    sku_cat_name: '全部商品',
                    sku_parent_cat_id: 'null' // 若已是顶级类目，传"null"
                  }],
                  "shipping_shop": {
                    "shipping_shop_id": merchantInfo.cloudMerchantId.toString(), // 到家类型对接智慧零售入口必传
                    "shipping_shop_name": "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
                  },
                  sale: {
                    original_price: parseFloat(cateProductList[i].price), // 对接智慧零售入口必传
                    current_price: parseFloat(cateProductList[i].price) // 对接智慧零售入口必传
                  },
                  primary_image_url: cateProductList[i].majorUrl
                  // more...
                });
              }
            }
            if (this.isdrawlots == 1) {
              let productArr = temporaryProductList;
              temporaryProductList = temporaryProductList.slice(0, 5);
            }
            this.drawControl(temporaryProductList)
            resolve(temporaryProductList)
          }).catch((err) => {
            // tip.plainText(err.msg)
          })
        })

      },
      //抽签时间控制
      async drawControl(listarr) {
        let listArr = listarr
        for (let i = 0; i < listArr.length; i++) {
          if (listArr[i].activitySelection) {
            listArr[i].activitySelection.dateStatus = await this.timeStatus(listArr[i]).dateStatus
            listArr[i].activitySelection.joinStatus = await this.timeStatus(listArr[i]).joinStatus
          }
        }
        this.productList = listArr
        this.hasDrawFlag = listArr.filter((item) => item.activitySelection).length > 0 ? true : false
      },
      timeStatus(item) {
        let nowTime = new Date().getTime()
        let drawStartTime = item.activitySelection.activitySelectionStartTime
        let drawEndTime = item.activitySelection.activitySelectionEndTime
        let promulgateTime = item.activitySelection.promulgateTime
        let buyEndTime = item.activitySelection.buyEndTime
        let activityStopTime = item.activitySelection.activityStopTime
        let obj = {}
        let showTime;
        let showText;
        if (nowTime < drawStartTime) {
          showTime = util.timeFormat(drawStartTime) + ' 开始登记'
          showText = '未开放登记信息'
        } else if (nowTime > drawStartTime && nowTime < drawEndTime) {
          showTime = util.timeFormat(drawEndTime) + ' 登记结束'
          showText = '开放登记信息'
        } else if (nowTime > drawEndTime && nowTime < promulgateTime) {
          showTime = util.timeFormat(promulgateTime) + ' 公布结果'
          showText = '等待公布结果'
        } else if (nowTime > promulgateTime && nowTime < buyEndTime) {
          showText = '结果已公布'
          showTime = util.timeFormat(buyEndTime) + ' 活动结束'
        } else if (nowTime > buyEndTime && nowTime < activityStopTime) {
          showTime = util.timeFormat(buyEndTime) + ' 活动结束'
          showText = '活动已结束'
        } else {
          showTime = ''
          showText = ''
        }
        obj.dateStatus = showTime
        obj.joinStatus = showText
        return obj
      },
      enterProductList(item) {
        uni.navigateTo({
          url: '/pages/item/categoryList?id=' + item.foreignId
        })
      }
    }
  }
</script>

<style lang="less">
  page {
    background-color: #f6f5f3;
  }

  /* 标题 */
  .titleBox {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 40rpx;

    .j_icon {
      background-image: url(https://100000063-1252208446.cos.ap-shanghai.myqcloud.com/images/miniprogram/%20images/category-bg.png);
      width: 220rpx;
      height: 50rpx;
      background-position: left;
      background-size: contain;
      background-repeat: no-repeat;
      padding-left: 45rpx;
      margin: 0 15rpx;
      font-size: 38rpx;
    }

    .mcl-youjiantou {
      font-size: 26rpx;
      margin: 0 25rpx 0 10rpx;
    }
  }

  /* banner */
  .bannerBox {
    margin: 20rpx 15rpx 0;
    background-color: #f9f9f9;
  }

  /* 列表 */
  .goodsList {
    margin: 15rpx 15rpx 0;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    image {
      width: 100%;
      display: block;
    }

    &.slideMod {
      overflow-x: auto;
      flex-wrap: nowrap;
      justify-content: left;

      .itemGoods {
        width: 406rpx;
        margin: 0 15rpx 0 0;
      }

      image {
        width: 406rpx;
        display: block;
      }
    }

    .itemGoods {
      text-align: center;
      width: 49%;
      background-color: #fff;
      margin-bottom: 15rpx;

      &:last-child {
        margin: 0;
      }

      .gTitle {
        color: #030303;
        width: 300rpx;
        margin: 0 auto 10rpx;
        line-height: 48rpx;
      }

      .gCapacity {
        color: #AEAEAE;
        font-size: 24rpx;
        margin-bottom: 18rpx;
      }

      .gPrice {
        font-size: 32rpx;
        margin-bottom: 20rpx;
      }

      .gBtn {
        margin: 0 auto 30rpx;
        width: 340rpx;
        height: 60rpx;
        background: #010101;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        font-size: 22rpx;
      }
    }
  }
</style>
